#region License
/* Copyright (c) 2011 Maksymilian Mulawa
	
Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, 
 * this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products 
 * derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using log4net;
using ReplicationExplorer.DomainModel.Infrastructure;
using ReplicationExplorer.DomainModel.Publisher.Entities;
using ReplicationExplorer.DomainModel.Subscriber.Entities;
using ReplicationExplorer.DomainModel.Subscriber.Repositories;

namespace ReplicationExplorer.Repositories
{
    public class SubscriptionRepository : ISubscriptionRepository
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(SubscriptionRepository));
        private readonly IDistributorSession _distributorSession;

        public SubscriptionRepository(IDistributorSession distributorSession)
        {
            _distributorSession = distributorSession;
        }

        public List<Subscription> GetPublications(Publication publication)
        {
            List<Subscription> publications = new List<Subscription>();
            try
            {
                string distributionDatabase = publication.PublisherServer.DistributionDatabase.Name;
                using (SqlConnection connection = new SqlConnection(_distributorSession.GetDistributionDatabaseConnectionString(distributionDatabase)))
                {
                    connection.Open();

                    //TODO:Set command timeout 
                    SqlCommand cmd = new SqlCommand(ReplicationExplorerSqlQueries.sp_replmonitorhelpsubscription, connection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = _distributorSession.SqlQueryTimeoutInSeconds;
                    cmd.Parameters.AddWithValue("@publisher", publication.PublisherServer.Name);
                    cmd.Parameters.AddWithValue("@publication", publication.Name);
                    cmd.Parameters.AddWithValue("@publication_type", publication.PublicationType);
                
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Subscription subscription = new Subscription();
                            subscription.Subscriber = (string) reader["subscriber"];
                            subscription.DistributorSession = _distributorSession;
                            //subscription.Id = (int)reader["subscriber_id"];
                            subscription.SubscriptionDatabase = (string)reader["subscriber_db"];
                            subscription.Type = (int)reader["subtype"];
                            subscription.Status = (int)reader["status"];
                            subscription.Warning = (int)reader["warning"];
                            //All three latency figures can be NULL
                            subscription.TimeToExpiration = DataReaderHelper.ReadInt(reader, "timetoexpiration");
                            subscription.DistributionAgentName = DataReaderHelper.ReadStrting(reader, "distribution_agentname");

                            subscription.LastTimeDistributionAgentRun = DataReaderHelper.ReadDateTime(reader, "last_distsync");
                            subscription.MergeAgentName = DataReaderHelper.ReadStrting(reader, "mergeagentname");

                            //EXTRA metadata
                            //SELECT DISTINCT publisher_db, subscriber_db, subscriber_id, independent_agent, sync_type, update_mode, publisher_seqno, ss_cplt_seqno FROM dbo.MSsubscriptions WHERE subscriber_id >= 0
                        
                        
                            publications.Add(subscription);
                        }
                    }

                }
            }
            catch (Exception e)
            {
                _log.Error(e);
                throw;
            }

            return publications;

        }
    }
}